package cn.zyjblogs.netty.http;

import com.sun.jndi.toolkit.url.Uri;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpObject;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.util.CharsetUtil;

import java.nio.charset.StandardCharsets;

/**
 * 说明
 * 1、SimpleChannelInboundHandler是ChannelInboundHandlerAdapter的子类
 * 2、HttpObject 客户端和服务端相互通讯的数据封装成HttpObject
 */
public class TestHttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {
    //当有读取客户数据的时候触发
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
        //判断msg是不是httprequest请求
        if (msg instanceof HttpRequest){
            System.out.println("对应的channel= "+ctx.channel() + " pipeline="+ctx.pipeline() +" 通过pipeline获取channel "+ctx.pipeline().channel());
            System.out.println("获取当前ctx的handler="+ctx.handler());
            System.out.println("pipeline hashCode=" + ctx.pipeline().hashCode()+" TestHttpServerHandler hash= "+this.hashCode());
            System.out.println("msg 类型="+ msg.getClass());
            System.out.println("客户端地址"+ctx.channel().remoteAddress());
            //获取到url
            HttpRequest httpRequest = (HttpRequest) msg;
            if ("/favicon.ico".equals(httpRequest.uri())){
                System.out.println("请求了"+httpRequest.uri()+"不做响应");
                return;
            }
            //回复信息给浏览器[http协议]
            ByteBuf buf = Unpooled.copiedBuffer("hello ,我是服务端", CharsetUtil.UTF_8);
            //够着一个http的响应，即httpResponse
            FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,buf);
            response.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/plain;charset=utf-8");
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH,buf.readableBytes());
            //将构建好的response返回
            ctx.writeAndFlush(response);
        }
    }

}
